package com.jic.finance.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.finance.common.util.BeanUtil;
import com.jic.finance.entity.PaymentGatewayConfig;
import com.jic.finance.request.manager.PaymentGatewayConfigRequest;
import com.jic.finance.response.manager.PaymentGatewayConfigResponse;
import com.jic.finance.service.PaymentGatewayConfigService;
import com.jic.util.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: zxl
 * @date: 2020-01-09
 * @remark: 支付配置网关管理系统的服务
 */
@Api("支付配置网关")
@RestController
@RequestMapping("/paymentGatewayConfig")
@Slf4j
public class PaymentGatewayConfigController extends BaseController{

    @Autowired
    private PaymentGatewayConfigService paymentGatewayConfigService;


    @Autowired
    private RedisClientTemplate redisClientTemplate;


    /**
     * 分页查询
     * @param form
     * @return
     */
    @ApiOperation(value = "获取所有支付配置网关列表")
    @ResponseBody
    @RequestMapping("/queryList")
    public RestResult<PageResult<PaymentGatewayConfigResponse>> queryList(@RequestBody PaymentGatewayConfigRequest form) {
        log.info("开始获取所有支付配置网关=========》,{}", form.toString());
        Page page = new Page();
        page.setLimit(form.getLimit());
        page.setStart(form.getStart());
        PaymentGatewayConfig paymentGateway = BeanUtil.copy(form, PaymentGatewayConfig.class);
        paymentGateway.setDeleteFlag(0);
        PageResult<PaymentGatewayConfig> result = paymentGatewayConfigService.queryPage(paymentGateway, page);
        List<PaymentGatewayConfigResponse> paymentGatewayResponseList = result.getRows().stream().map(temp -> {
            PaymentGatewayConfigResponse paymentGatewayConfigResponse = BeanUtil.copy(temp, PaymentGatewayConfigResponse.class);
            return paymentGatewayConfigResponse;
        }).filter(item -> item != null).collect(Collectors.toList());
        PageResult<PaymentGatewayConfigResponse> pageResult = new PageResult<>();
        pageResult.setRows(paymentGatewayResponseList);
        pageResult.setTotal(result.getTotal());
        return RestResult.success(pageResult);
    }



    /*
     * 新增/修改支付配置网关
     * */
    @ApiOperation(value = "新增/修改支付配置网关")
    @ResponseBody
    @RequestMapping("/editPaymentConfigGateway")
    public RestResult<String> editCurrencyManage(@RequestBody PaymentGatewayConfigRequest form) {
        log.info("开始进入新增/修改支付配置网关=========》,{}", form.toString());
        RestResult restResult = new RestResult<>();
        try {
            if (StringUtils.isEmpty(form.getToken())){
                throw new Exception("必传参数为空 token");
            }
            String userStr = redisClientTemplate.get(form.getToken());
            if (StringUtils.isEmpty(userStr)){
                return RestResult.error("4000","登录失效");
            }
            Map sysUser = JSONArray.parseObject(userStr, Map.class);
            PaymentGatewayConfig paymentGateway = BeanUtil.copy(form, PaymentGatewayConfig.class);
            //修改
            if(null!=paymentGateway.getGatewayId()&&!"".equals (paymentGateway.getGatewayId())){
                //先删除后插入
                paymentGatewayConfigService.delete(paymentGateway.getGatewayId());
                paymentGateway.setCreator(Long.parseLong(sysUser.get("id").toString()));
                paymentGateway.setCreatorName(sysUser.get("username").toString());
                JSONObject jsonObj = JSONObject.parseObject(form.getJson());
                //map对象
                Map<String, Object> data =new HashMap<>();
                //循环转换
                Iterator it =jsonObj.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
                    data.put(entry.getKey(), entry.getValue());
                    paymentGateway.setDeleteFlag(0);
                    paymentGateway.setParamKey(entry.getKey());
                    paymentGateway.setParamType(1);
                    paymentGateway.setParamValue(entry.getValue().toString());
                    paymentGateway.setDeptId(Long.valueOf(sysUser.get("deptId").toString()));
                    long flag=paymentGatewayConfigService.insert(paymentGateway);
                }
                restResult=RestResult.success(restResult);
                restResult=RestResult.success(restResult);
            }else {
                paymentGateway.setCreator(Long.parseLong(sysUser.get("id").toString()));
                paymentGateway.setCreatorName(sysUser.get("username").toString());
                paymentGateway.setGatewayId(form.getId());
                JSONObject jsonObj = JSONObject.parseObject(form.getJson());
               //map对象
                Map<String, Object> data =new HashMap<>();
               //循环转换
                Iterator it =jsonObj.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
                    data.put(entry.getKey(), entry.getValue());
                    paymentGateway.setDeleteFlag(0);
                    paymentGateway.setParamKey(entry.getKey());
                    paymentGateway.setParamType(1);
                    paymentGateway.setParamValue(entry.getValue().toString());
                    paymentGateway.setDeptId(Long.valueOf(sysUser.get("deptId").toString()));
                    long flag=paymentGatewayConfigService.insert(paymentGateway);
                }
                restResult=RestResult.success(restResult);
            }

        } catch (Exception e) {
            log.error("error",e);
            restResult=RestResult.error("9999",e.getLocalizedMessage());
        }
        return restResult;
    }


    /*
     * 删除支付配置网关
     * */
    @ApiOperation(value = "删除支付配置网关")
    @ResponseBody
    @RequestMapping("/deleteInfo")
    public RestResult<String> deleteInfo(String ids) {
        log.info("开始进入新增/删除支付配置网关=========》,{}", ids);
        RestResult restResult = new RestResult<>();
        try {
            String[] checked = ids.split(",");
            for(int i=0;i<checked.length;i++){
                paymentGatewayConfigService.delete(Long.valueOf(checked[i]));
            }
            restResult.setCode("0000");
        } catch (Exception e) {
            log.error("error",e);
            restResult=RestResult.error("9999",e.getLocalizedMessage());
        }
        return restResult;
    }

}
